package com.android.dumiaogou.fragment.member;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.dumiaogou.R;
import com.android.dumiaogou.activity.BaseObject;
import com.android.dumiaogou.activity.DirectBuyPayOrderActivity;
import com.android.dumiaogou.fragment.BaseLazyFragment;
import com.android.dumiaogou.model.data;
import com.android.dumiaogou.model.dataCallback;
import com.android.dumiaogou.model.member.DirectBuyOrderDetail;
import com.android.dumiaogou.model.member.DirectBuyOrderDetailCallback;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.dialog.MainMsg;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * 订单详情页
 */
public class Fragment_Mine_DirectBuy_Order_Detail extends BaseLazyFragment {


    @BindView(R.id.firmorder_address_name)
    TextView addressName;
    @BindView(R.id.firmorder_address_phone)
    TextView addressPhone;
    @BindView(R.id.firmorder_address_address)
    TextView addressAddress;
    @BindView(R.id.ll_orderdetail_goods_img)
    ImageView orderGoodsImg;
    @BindView(R.id.firmorder_goods_title)
    TextView orderGoodsTitle;
    @BindView(R.id.firmorder_goods_money)
    TextView orderGoodsPrice;
    @BindView(R.id.firmorder_goods_score)
    TextView orderGoodsScore;
    @BindView(R.id.firmorder_goods_total_score)
    TextView orderTotalScore;
    @BindView(R.id.ll_orderdetail_goods_price2)
    TextView orderTotalPrice;
    @BindView(R.id.ll_orderdetail_goods_paystyle)
    TextView orderGoodsPaystyle;
    @BindView(R.id.scroll)
    ScrollView scroll;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.button_next)
    TextView next;
    @BindView(R.id.tv_right)
    TextView tv_right;
    @BindView(R.id.rl_pay)
    RelativeLayout rlPay;
    @BindView(R.id.ll_express)
    LinearLayout llExpress;
    @BindView(R.id.ll_express_number)
    LinearLayout llExpressNum;
    @BindView(R.id.orderdetail_status)
    TextView tv_status;
    @BindView(R.id.orderdetail_express)
    TextView tv_express;
    @BindView(R.id.orderdetail_express_number)
    TextView tv_expressNum;
    @BindView(R.id.tv_line)
    TextView tv_line;

    private FragmentActivity mcontext;
    private View view;
    private boolean networkConnected;
    private static final String ARG_PARAM1 = "param1";
    private String order_sn;
    private String order_id;
    private String goods_img_src;
    private int status_id;

    private MainMsg mainMsg;
    DirectBuyOrderDetail.DataBean dataBean;
    DirectBuyOrderDetail.DataBean.GoodsBean goodsBean;

    public Fragment_Mine_DirectBuy_Order_Detail() {

    }

    public static Fragment_Mine_DirectBuy_Order_Detail newInstance(String need_id) {
        Fragment_Mine_DirectBuy_Order_Detail fragment = new Fragment_Mine_DirectBuy_Order_Detail();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, need_id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            order_sn = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    protected void initPrepare() {
        initUI();
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        GetDataOrder(order_sn);
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(Fragment_Mine_DirectBuy_Order.DIRECTBUY_ORDER_PAY);
        myIntentFilter.addAction(Fragment_Mine_DirectBuy_Order.DIRECTBUY_ORDER_COMMENT);
        //注册广播
        mcontext.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_mine_directbuy_order_detail, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        tv_right.setVisibility(View.INVISIBLE);
        return view;
    }

    private void initUI() {
        scroll.smoothScrollTo(0, 0);
    }

    @OnClick({R.id.button_next
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_next:
                toNext();
                break;
        }
    }

    //网络数据
    private void GetDataOrder(String id) {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDERDETAIL + "?order_sn=" + id;

        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.get(address, header, null, detailCallback);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    DirectBuyOrderDetailCallback detailCallback = new DirectBuyOrderDetailCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(DirectBuyOrderDetail response, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            dataBean = response.getData();
            if (response.getCode() == 0 && dataBean != null) {
                setViewShow(true);
                switchStatus(dataBean);
                tv_status.setText(dataBean.getStatus_name());
                if(dataBean.getExpress_num()!=null&&!dataBean.getExpress_num().equals("")){
                    tv_expressNum.setText(dataBean.getExpress_num());
                    tv_express.setText(dataBean.getExpress_name());
                }
                order_id = dataBean.getId();
                order_sn = dataBean.getOrder_sn();
                addressName.setText(dataBean.getName());
                addressPhone.setText(dataBean.getMobile());
                addressAddress.setText(dataBean.getArea() + dataBean.getAddress());
                goodsBean = dataBean.getGoods().get(0);
                orderGoodsTitle.setText(goodsBean.getGoods_name());
                orderGoodsPrice.setText("¥" + goodsBean.getSell_price());
                orderTotalPrice.setText("¥" + dataBean.getOrder_amount());
                orderGoodsScore.setText(goodsBean.getScore_price() + "积分");
                orderTotalScore.setText(dataBean.getScore_amount() + "积分");
                goods_img_src = goodsBean.getImg_cover();
                ObjectUtils.photo(mcontext, goods_img_src, orderGoodsImg);
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                orderGoodsPaystyle.setText(dataBean.getPay_name());
            } else {
                noData.setVisibility(View.VISIBLE);
                noDataTv.setText(response.getMsg());
                noDataTv.setVisibility(View.VISIBLE);
            }
        }
    };

    private void switchStatus(DirectBuyOrderDetail.DataBean data) {
        status_id = data.getStatus_id();
        switch (status_id) {
            case 100:
                setViewShow(false);
                next.setText("去支付");
                break;
            case 101:
                next.setVisibility(View.GONE);
                break;
            case 102:
                next.setText("确认收货");
                break;
            case 110:
                if(data.getIs_rate().equals("1")){
                    next.setText("查看评价");
                }else{
                    next.setText("去评价");
                }
                next.setBackgroundResource(R.drawable.corner_yellow_bg);
                break;
            case 111:
                next.setText("已取消");
                next.setBackgroundResource(R.drawable.corner_gray_bg);
                break;
        }
    }

    private void setViewShow(boolean b) {
        if(b){
            rlPay.setVisibility(View.VISIBLE);
            tv_line.setVisibility(View.VISIBLE);
            llExpress.setVisibility(View.VISIBLE);
            llExpressNum.setVisibility(View.VISIBLE);
        }else {
            rlPay.setVisibility(View.GONE);
            tv_line.setVisibility(View.GONE);
            llExpress.setVisibility(View.GONE);
            llExpressNum.setVisibility(View.GONE);
        }
    }

    private void toNext() {
        status_id = dataBean.getStatus_id();
        switch (status_id) {
            case 100:
                Intent intent_pay = new Intent(mcontext, DirectBuyPayOrderActivity.class);
                intent_pay.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_ORDER_ID, order_sn);
                startActivity(intent_pay);
                break;
            case 102:
                mainMsg = new MainMsg(mcontext);
                mainMsg.show(mcontext.getWindow().getDecorView(), 0, "是否确认收到货物？");
                mainMsg.setOnSetSureClickListener(new MainMsg.OnSetSureClickListener() {
                    @Override
                    public void onSure() {
                        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDERQUERENSHOUHUO + "?id=" + order_id;
                        getData(address);
                        mainMsg.close();
                    }
                });
                break;
            case 110:
                if(dataBean.getIs_rate().equals("1")){
                    Intent intent = new Intent(mcontext, BaseObject.class);
                    intent.putExtra("title", "商品评价");
                    intent.putExtra("need_id", goodsBean.getGood_id());
                    mcontext.startActivity(intent);
                }else{
                    Intent intent_rate = new Intent(mcontext, BaseObject.class);
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "评价");
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_GOOD_ID, goodsBean.getGood_id());
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_ID, goodsBean.getOrder_id());
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_BUY_NUM, goodsBean.getBuy_num());
                    intent_rate.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_THUMB, goodsBean.getImg_cover());
                    startActivity(intent_rate);
                }
                break;
        }
    }

    private void getData(String url) {
        progress.setVisibility(View.VISIBLE);
        HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
        HttpUtils.get(url, header, null, new dataCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                progress.setVisibility(View.GONE);
                ObjectUtils.toast(mcontext, "网络连接出现异常");
            }

            @Override
            public void onResponse(data response, int id) {
                progress.setVisibility(View.GONE);
                ObjectUtils.toast(mcontext, response.getMsg());
                if (response.getCode() == 0) {
                    GetDataOrder(order_sn);
                    Intent mIntent = new Intent(Fragment_Mine_DirectBuy_Order.DIRECTBUY_ORDER_SHOUHUO);
                    mcontext.sendBroadcast(mIntent);
                }
            }
        });
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            GetDataOrder(order_sn);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mBroadcastReceiver);
        mBroadcastReceiver = null;
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        GetDataOrder(order_sn);
    }
}
